package xq.gwt.ui.widgets.command;


import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.events.ClickHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import xq.gwt.mvc.controller.CommandController;
import xq.gwt.mvc.model.CommandModel;
import xq.gwt.mvc.view.CommandView;
import xq.gwt.mvc.view.ObservableViewImp;
import xq.gwt.ui.widgets.feedback.DefaultExceptionPresenter;
import xq.gwt.ui.widgets.feedback.DefaultFeedbackPresenter;

public class MenuItemCommandPresenter extends ObservableViewImp implements CommandView {
	protected CommandController controller;
	protected MenuItem menuItem;
	
	public MenuItemCommandPresenter(){
		menuItem = new MenuItem();
		init();
	}
	
	public MenuItemCommandPresenter(MenuItem menuItem){
		this.menuItem = menuItem;
		init();
	}

	private void init(){
		menuItem.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(MenuItemClickEvent event) {
				notifyViewChangedListeners();				
			}
		});
		
		
		controller = new CommandController(this);
	}
	
	@Override
	public void setEnabled(boolean enabled) {
		menuItem.setEnabled(enabled);		
	}

	@Override
	public void showFeedback(String feedback) {
		DefaultFeedbackPresenter presenter = new DefaultFeedbackPresenter();
		presenter.showFeedback(feedback);
		
	}

	@Override
	public void reportException(Exception ex) {
		DefaultExceptionPresenter exPresenter = new DefaultExceptionPresenter();
		exPresenter.showException(ex);
		
	}

	@Override
	public void executeStarted() {
		menuItem.setEnabled(false);
		
	}

	@Override
	public void excuteFinished() {
		menuItem.setEnabled(true);
		
	}

	@Override
	public void setCaption(String caption) {
		menuItem.setTitle(caption);
		
	}
	
	public MenuItem getMenuItem() {
		return menuItem;
	}
	
	public void setModel(CommandModel model){
		controller.setCommandModel(model);
	}
}
